package com.nbjtjc.safe.service.safe;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.nbjtjc.safe.mapper.safe.SafeUserPlanMapper;
import com.nbjtjc.safe.model.safe.SafeDangerInspectPlan;
import com.nbjtjc.safe.model.safe.SafeUserPlan;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class SafeUserPlanServiceImpl {
    @Autowired
    private SafeUserPlanMapper safeUserPlanMapper;

    public void addBatch(SafeDangerInspectPlan safeDangerInspectPlan) {
        if (ObjectUtil.isNotNull(safeDangerInspectPlan)
                && CollectionUtil.isNotEmpty(safeDangerInspectPlan.getSafeUserPlanList())) {
            safeDangerInspectPlan.getSafeUserPlanList().forEach(safeUserPlan -> {
                safeUserPlan.setPlanId(safeDangerInspectPlan.getId());
            });
            safeUserPlanMapper.insertList(safeDangerInspectPlan.getSafeUserPlanList());
        }
    }

    public void updateSafeUserPlan(List<SafeUserPlan> userPlans, SafeDangerInspectPlan plan) {
        List<SafeUserPlan> safeUserPlanList = safeUserPlanMapper.findByPlanId(plan.getId());
        Set<Integer> addUserIds = new HashSet<>();
        Set<Integer> originalUserIds = new HashSet<>();
        Set<Integer> deleteUserIds = new HashSet<>();
        originalUserIds.addAll(safeUserPlanList.stream()
                .map(SafeUserPlan::getUserId).collect(Collectors.toSet()));
        addUserIds.addAll(userPlans.stream()
                .map(SafeUserPlan::getUserId).collect(Collectors.toSet()));
        deleteUserIds.addAll(originalUserIds);

        deleteUserIds.removeAll(addUserIds);
        addUserIds.removeAll(originalUserIds);
        safeUserPlanList.forEach(safeUserPlan -> {
            if (addUserIds.contains(safeUserPlan.getUserId())) {
                safeUserPlan.setPlanId(plan.getId());
                safeUserPlanMapper.insert(safeUserPlan);
            }
            if (deleteUserIds.contains(safeUserPlan.getUserId())) {
                Example deleteExample = new Example(SafeUserPlan.class);
                deleteExample.and().andEqualTo("planId", plan.getId())
                        .andEqualTo("userId", safeUserPlan.getUserId());
                safeUserPlanMapper.deleteByExample(deleteExample);
            }
        });
    }

}
